<?php

namespace app\proxyapi\controller;

use app\appapi\service\TrainService;
use app\data\model\LiveAppproxy;
use app\data\model\LiveIndustryList;
use app\data\model\LiveIntegralRecord;
use app\data\model\LiveProxyList;
use app\data\model\LiveThaliList;
use app\data\model\LiveUserList;
use think\admin\Exception;
use think\facade\Db;

class ManageUser extends BaseProxyController
{
    //获取套餐、行业列表
    public function getThaliIndustryList(){
        $userId = $this->checkTokenReturnUserId();
        $post = $this->request->post();
        if(!isset($post['appName'], $post['packageName'], $post['versionName'], $post['versionCode'])) $this->error('缺少参数！');
        $app = LiveAppproxy::mk()->where(['app_name'=>$post['appName'],'app_package'=>$post['packageName'],'deleted'=>0])->find();
        if(empty($app)) $this->error('不存在当前应用！');

        $thalis = LiveThaliList::mk()->field('thali_id,thali_name,vip_amount,qa_amount,train_amount')->where(['deleted'=>0])->select()->toArray();
        $industrys = LiveIndustryList::mk()->field('industry_id,industry_name')->where(['deleted'=>0])->select()->toArray();
        $this->success('success',['thalis'=>$thalis,'industrys'=>$industrys]);
    }
    //用户列表
    public function getUserList(){
        $userId = $this->checkTokenReturnUserId();
        $post = $this->request->post();
        if(!isset($post['appName'], $post['packageName'], $post['versionName'], $post['versionCode'])) $this->error('缺少参数！');
        $app = LiveAppproxy::mk()->where(['app_name'=>$post['appName'],'app_package'=>$post['packageName'],'deleted'=>0])->find();
        if(empty($app)) $this->error('不存在当前应用！');

        //当前用户
        $users = LiveUserList::mk()
            ->field('id as uuid,user_nickname,user_name,qa_status,qa_endtime,train_status,train_endtime,thali_starttime,thali_endtime,login_versionName,create_time')
            ->where(['pid'=>$userId])->select()->toArray();
        $this->success('success',$users);
    }
    //新增用户
    public function addUser(){
        $userId = $this->checkTokenReturnUserId();
        $post = $this->request->post();
        if(!isset($post['user_nickname'], $post['user_name'], $post['user_password'], $post['industry_id'], $post['thali_id'])) $this->error('缺少参数！');

        if (strpos($post['user_nickname'], " ") !== false)  $this->error('昵称含有空格！');
        if (strpos($post['user_name'], " ") !== false)  $this->error('账户含有空格！');
        if (strpos($post['user_password'], " ") !== false)  $this->error('密码含有空格！');
        if(empty($post['industry_id'])) $this->error('请选择行业！');
        if(empty($post['thali_id'])) $this->error('请选择套餐！');
        if(LiveUserList::mk()->where(['user_name'=>$post['user_name']])->count() > 0) $this->error('账户名已存在，请更换！');

        //到期时间
        $thali = LiveThaliList::mk()->where(['thali_id'=>$post['thali_id']])->find();
        if($thali['thali_type'] == 1){
            //时间类型 1日卡 2月卡
            $end_time = date("Y-m-d H:i:s",strtotime('+ '.$thali['day_num'].' days'));
        }else{
            $end_time = date("Y-m-d H:i:s",strtotime('+ '.$thali['month_num'].' months'));
        }
        //当前用户
        $proxy = LiveProxyList::mk()->where(['id'=>$userId,'deleted'=>0])->find();
        if($proxy['integral_balance'] < $thali['vip_amount']) $this->error('积分余额不足！');

        Db::startTrans();// 开启事务
        try {
            //新建用户
            LiveUserList::mk()->insertGetId([
                'pid'               =>$userId,
                'app_id'            => $proxy['app_id'],
                'user_nickname'     => $post['user_nickname'],
                'user_name'         => $post['user_name'],
                'user_password'     => $post['user_password'],
                'industry_id'       => $post['industry_id'],
                'thali_type'        => 1,//套餐状态 0未购买 1已购买
                'thali_id'          =>$post['thali_id'],
                'thali_starttime'   =>date("Y-m-d H:i:s"),
                'thali_endtime'     =>$end_time,
                'create_userid'     =>$userId,
            ]);
            //积分记录-支出
            $new_integral_balance = $proxy['integral_balance'] - $thali['vip_amount'];
            LiveProxyList::mk()->where(['id'=>$userId,'deleted'=>0])->update(['integral_balance'=>$new_integral_balance]);
            LiveIntegralRecord::mk()->insert([
                'uuid'              =>$userId,
                'app_id'            =>$proxy['app_id'],
                'integral_type'     =>2,//积分类型 1收入 2支出
                'integral_num'      =>-$thali['vip_amount'],
                'integral_balance'  =>$new_integral_balance,
                'create_uuid'       =>$userId,
                'remarks'=>'新增用户['.$post['user_nickname'].'：'.$post['user_name'].']，扣除['.$thali['vip_amount'].']积分'
            ]);

            Db::commit();// 事务完成保存
            $this->success('新增成功',$new_integral_balance);
        } catch (Exception $exception) {
            Db::rollback();// 事务回滚
            $this->error('新增失败');
        }
    }
    //套餐续费
    public function reUserVip(){
        $userId = $this->checkTokenReturnUserId();
        $post = $this->request->post();
        if(!isset($post['thali_id'], $post['uuid'])) $this->error('缺少参数！');

        //计算套餐时间
        $thali = LiveThaliList::mk()->where(['thali_id'=>$post['thali_id']])->find();
        $user = LiveUserList::mk()->where(['id'=>$post['uuid']])->find();
        if(empty($user['thali_endtime']) || $user['thali_endtime'] < date('Y-m-d H:i:s')){
            //【为空】 或 【到期了】  时间类型 1日卡 2月卡
            if($thali['thali_type'] == 1) $end_time = date("Y-m-d H:i:s",strtotime('+ '.$thali['day_num'].' days'));
            else $end_time = date("Y-m-d H:i:s",strtotime('+ '.$thali['month_num'].' months'));
            $start_time = date("Y-m-d H:i:s");
        }else{
            $start_time = $user['thali_starttime'];
            //【未到期】
            if($thali['thali_type'] == 1) $end_time = date("Y-m-d H:i:s",strtotime('+ '.$thali['day_num'].' days',strtotime($user['thali_endtime'])));
            else $end_time = date("Y-m-d H:i:s",strtotime('+ '.$thali['month_num'].' months',strtotime($user['thali_endtime'])));
        }

        //当前用户
        $proxy = LiveProxyList::mk()->where(['id'=>$userId,'deleted'=>0])->find();
        if($proxy['integral_balance'] < $thali['vip_amount']) $this->error('积分余额不足！');

        Db::startTrans();// 开启事务
        try {
            //更新内容
            $userQuery = LiveUserList::mk()->where(['id' => $post['uuid']]);
            $user = $userQuery->find();
            $userQuery->update([
                'thali_id'          => $post['thali_id'],
                'thali_type'         => 1,//套餐状态 0未购买 1已购买
                'thali_starttime'    => $start_time,
                'thali_endtime'      => $end_time,
            ]);
            //积分记录-支出
            $new_integral_balance = $proxy['integral_balance'] - $thali['vip_amount'];
            LiveProxyList::mk()->where(['id'=>$userId,'deleted'=>0])->update(['integral_balance'=>$new_integral_balance]);
            LiveIntegralRecord::mk()->insert([
                'uuid'              =>$userId,
                'app_id'            =>$proxy['app_id'],
                'integral_type'     =>2,//积分类型 1收入 2支出
                'integral_num'      =>-$thali['vip_amount'],
                'integral_balance'  =>$new_integral_balance,
                'create_uuid'       =>$userId,
                'remarks'=>'套餐续费['.$user['user_nickname'].'：'.$user['user_name'].']，扣除['.$thali['vip_amount'].']积分'
            ]);

            Db::commit();// 事务完成保存
            $this->success('续费成功',$new_integral_balance);
        } catch (Exception $exception) {
            Db::rollback();// 事务回滚
            $this->error('续费失败');
        }
    }
    //获取AI问答加购信息
    public function getUserAiQa(){
        $userId = $this->checkTokenReturnUserId();
        $post = $this->request->post();
        $this->error('暂不支持AI问答加购！');
        if(!isset($post['uuid'])) $this->error('缺少参数！');

        //计算套餐时间
        $user = LiveUserList::mk()->where(['id'=>$post['uuid']])->find();
        $thali = LiveThaliList::mk()->where(['thali_id'=>$user['thali_id']])->find();
        if($user['thali_endtime'] < date('Y-m-d H:i:s')) $this->error('请先【套餐续费】才可以进行【AI问答加购】！');
        if($user['qa_endtime'] == $user['thali_endtime'] && $user['qa_status'] == 1) $this->error('【AI问答加购】已加购到【套餐结束时间】，无需加购！');
        //获取剩余分区个数
        $residue_partition = 0;
        //查询该套餐剩余天数，并计算需要充值的积分
        if($user['qa_status'] == 0){
            foreach (TrainService::CollectionNameArray as $name){
                $re = TrainService::instance()->dashVectorPartitionList($name);
                if($re['code'] == 0 && count($re['output']) < 128){
                    $residue_partition = 128 - count($re['output']);
                    break;
                }
            }
            if($residue_partition == 0) $this->error('暂无训练分区资源，请联系技术!');

            $residue_second = abs(strtotime($user['thali_endtime']) - time());
        }else{
            $residue_second = abs(strtotime($user['thali_endtime']) - strtotime($user['qa_endtime']));
        }
        $residue_day = floor($residue_second / 86400);
        //需要充值的积分 = 问答功能金额 / 30 * 剩余天数  最后取整
        $residue_inte = floor($thali['qa_amount'] / 30 * $residue_day);

        $msg = "为账户【".$user['user_nickname']."：".$user['user_name']."】加购【AI问答训练】至套餐结束时间【".$user['thali_endtime']."】，剩余天数【".$residue_day."】，套餐积分【".$thali['qa_amount']."】，将消耗【".$residue_inte."】积分（公式：消耗积分 = 套餐积分 / 30 * 剩余天数）";

        $this->success('success',['residue_inte'=>$residue_inte,'msg'=>$msg,'uuid'=>$post['uuid'],'type'=>'AiQa']);
    }
    //AI问答加购
    public function reUserAiQa(){
        $userId = $this->checkTokenReturnUserId();
        $post = $this->request->post();
        $this->error('暂不支持AI问答加购！');
        if(!isset($post['uuid'])) $this->error('缺少参数！');

        //计算套餐时间
        $user = LiveUserList::mk()->where(['id'=>$post['uuid']])->find();
        $thali = LiveThaliList::mk()->where(['thali_id'=>$user['thali_id']])->find();
        if($user['thali_endtime'] < date('Y-m-d H:i:s')) $this->error('请先【套餐续费】才可以进行【AI问答加购】！');
        if($user['qa_endtime'] == $user['thali_endtime'] && $user['qa_status'] == 1) $this->error('【AI问答加购】已加购到【套餐结束时间】，无需加购！');

        //获取剩余分区个数
        $residue_partition = 0;
        //获取可新增分区的集合
        $qa_collection = "";

        //查询该套餐剩余天数，并计算需要充值的积分
        if($user['qa_status'] == 0){
            foreach (TrainService::CollectionNameArray as $name){
                $re = TrainService::instance()->dashVectorPartitionList($name);
                if($re['code'] == 0 && count($re['output']) < 128){
                    $qa_collection = $name;
                    $residue_partition = 128 - count($re['output']);
                    break;
                }
            }
            if($residue_partition == 0) $this->error('暂无分区资源，请联系技术!');

            $residue_second = abs(strtotime($user['thali_endtime']) - time());

        }else{
            $residue_second = abs(strtotime($user['thali_endtime']) - strtotime($user['qa_endtime']));
        }
        $residue_day = floor($residue_second / 86400);
        //需要充值的积分 = 问答功能金额 / 30 * 剩余天数  最后取整
        $residue_inte = floor($thali['qa_amount'] / 30 * $residue_day);

        //当前用户
        $proxy = LiveProxyList::mk()->where(['id'=>$userId,'deleted'=>0])->find();
        if($proxy['integral_balance'] < $residue_inte) $this->error('积分余额不足！');

        Db::startTrans();// 开启事务
        try {
            if($user['qa_status'] == 0) {
                //没有分配分区 则创建分区
                TrainService::instance()->dashVectorCreatePartition('userid_qa_'.$post['uuid'],$qa_collection);
                LiveUserList::mk()->where(['id' => $post['uuid']])->update([
                    'qa_collection'     => $qa_collection,//问答集合名称
                    'qa_status'         => 1,//问答订购状态0未订购 1已订购
                ]);
            }
            //更新内容
            LiveUserList::mk()->where(['id' => $post['uuid']])->update([
                'qa_endtime'        => $user['thali_endtime'],//问答订购结束时间
            ]);

            //积分记录-支出
            $new_integral_balance = $proxy['integral_balance'] - $residue_inte;
            LiveProxyList::mk()->where(['id'=>$userId,'deleted'=>0])->update(['integral_balance'=>$new_integral_balance]);
            LiveIntegralRecord::mk()->insert([
                'uuid'              =>$userId,
                'app_id'            =>$proxy['app_id'],
                'integral_type'     =>2,//积分类型 1收入 2支出
                'integral_num'      =>-$residue_inte,
                'integral_balance'  =>$new_integral_balance,
                'create_uuid'       =>$userId,
                'remarks'=>'AI问答加购['.$user['user_nickname'].'：'.$user['user_name'].']，扣除['.$residue_inte.']积分'
            ]);

            Db::commit();// 事务完成保存
            $this->success('加购成功',$new_integral_balance);
        } catch (Exception $exception) {
            Db::rollback();// 事务回滚
            $this->error('加购失败');
        }
    }
    //获取AI训练加购信息
    public function getUserAiTrain(){
        $userId = $this->checkTokenReturnUserId();
        $post = $this->request->post();
        $this->error('暂不支持AI训练加购！');
        if(!isset($post['uuid'])) $this->error('缺少参数！');

        //计算套餐时间
        $user = LiveUserList::mk()->where(['id'=>$post['uuid']])->find();
        $thali = LiveThaliList::mk()->where(['thali_id'=>$user['thali_id']])->find();
        if($user['thali_endtime'] < date('Y-m-d H:i:s')) $this->error('请先【套餐续费】才可以进行【AI训练加购】！');
        if($user['qa_status'] == 0) $this->error('请先【AI问答加购】才可以进行【AI训练加购】！');
        if($user['train_endtime'] == $user['thali_endtime'] && $user['train_status'] == 1) $this->error('【AI训练加购】已加购到【套餐结束时间】，无需加购！');

        //获取剩余分区个数
        $residue_partition = 0;

        //查询该套餐剩余天数，并计算需要充值的积分
        if($user['train_status'] == 0){
            foreach (TrainService::CollectionNameArray as $name){
                $re = TrainService::instance()->dashVectorPartitionList($name);
                if($re['code'] == 0 && count($re['output']) < 128){
                    $residue_partition = 128 - count($re['output']);
                    break;
                }
            }
            if($residue_partition == 0) $this->error('暂无训练分区资源，请联系技术!');

            $residue_second = abs(strtotime($user['thali_endtime']) - time());
        }else{
            $residue_second = abs(strtotime($user['thali_endtime']) - strtotime($user['train_endtime']));
        }
        $residue_day = floor($residue_second / 86400);
        //需要充值的积分 = 问答功能金额 / 30 * 剩余天数  最后取整
        $residue_inte = floor($thali['train_amount'] / 30 * $residue_day);

        $msg = "为账户【".$user['user_nickname']."：".$user['user_name']."】加购【AI知识库训练】至套餐结束时间【".$user['thali_endtime']."】，剩余天数【".$residue_day."】，套餐积分【".$thali['train_amount']."】，将消耗【".$residue_inte."】积分（公式：消耗积分 = 套餐积分 / 30 * 剩余天数）";

        $this->success('success',['residue_inte'=>$residue_inte,'msg'=>$msg,'uuid'=>$post['uuid'],'type'=>'AiTrain']);
    }
    //AI训练加购
    public function reUserAiTrain(){
        $userId = $this->checkTokenReturnUserId();
        $post = $this->request->post();
        $this->error('暂不支持AI训练加购！');
        if(!isset($post['uuid'])) $this->error('缺少参数！');

        //计算套餐时间
        $user = LiveUserList::mk()->where(['id'=>$post['uuid']])->find();
        $thali = LiveThaliList::mk()->where(['thali_id'=>$user['thali_id']])->find();
        if($user['thali_endtime'] < date('Y-m-d H:i:s')) $this->error('请先【套餐续费】才可以进行【AI训练加购】！');
        if($user['qa_status'] == 0) $this->error('请先【AI问答加购】才可以进行【AI训练加购】！');
        if($user['train_endtime'] == $user['thali_endtime'] && $user['train_status'] == 1) $this->error('【AI训练加购】已加购到【套餐结束时间】，无需加购！');

        //获取剩余分区个数
        $residue_partition = 0;
        //获取可新增分区的集合
        $train_collection = "";

        //查询该套餐剩余天数，并计算需要充值的积分
        if($user['train_status'] == 0){
            foreach (TrainService::CollectionNameArray as $name){
                $re = TrainService::instance()->dashVectorPartitionList($name);
                if($re['code'] == 0 && count($re['output']) < 128){
                    $train_collection = $name;
                    $residue_partition = 128 - count($re['output']);
                    break;
                }
            }
            if($residue_partition == 0) $this->error('暂无分区资源，请联系技术!');

            $residue_second = abs(strtotime($user['thali_endtime']) - time());
        }else{
            $residue_second = abs(strtotime($user['thali_endtime']) - strtotime($user['train_endtime']));
        }
        $residue_day = floor($residue_second / 86400);
        //需要充值的积分 = 问答功能金额 / 30 * 剩余天数  最后取整
        $residue_inte = floor($thali['train_amount'] / 30 * $residue_day);

        //当前用户
        $proxy = LiveProxyList::mk()->where(['id'=>$userId,'deleted'=>0])->find();
        if($proxy['integral_balance'] < $residue_inte) $this->error('积分余额不足！');

        Db::startTrans();// 开启事务
        try {
            if($user['train_status'] == 0) {
                //没有分配分区 则创建分区
                TrainService::instance()->dashVectorCreatePartition('userid_'.$post['uuid'],$train_collection);
                LiveUserList::mk()->where(['id' => $post['uuid']])->update([
                    'train_collection'     => $train_collection,//问答集合名称
                    'train_status'         => 1,//问答订购状态0未订购 1已订购
                ]);
            }
            //更新内容
            LiveUserList::mk()->where(['id' => $post['uuid']])->update([
                'train_endtime'        => $user['thali_endtime'],//问答订购结束时间
            ]);

            //积分记录-支出
            $new_integral_balance = $proxy['integral_balance'] - $residue_inte;
            LiveProxyList::mk()->where(['id'=>$userId,'deleted'=>0])->update(['integral_balance'=>$new_integral_balance]);
            LiveIntegralRecord::mk()->insert([
                'uuid'              =>$userId,
                'app_id'            =>$proxy['app_id'],
                'integral_type'     =>2,//积分类型 1收入 2支出
                'integral_num'      =>-$residue_inte,
                'integral_balance'  =>$new_integral_balance,
                'create_uuid'       =>$userId,
                'remarks'           =>'AI训练加购['.$user['user_nickname'].'：'.$user['user_name'].']，扣除['.$residue_inte.']积分'
            ]);

            Db::commit();// 事务完成保存
            $this->success('加购成功',$new_integral_balance);
        } catch (Exception $exception) {
            Db::rollback();// 事务回滚
            $this->error('加购失败');
        }
    }
}